<?php

namespace app\admin\validate;

use think\Validate;
use think\facade\Db;

class MemberValidate extends Validate
{
    protected $rule = [
        'id' => 'require',
        'email' => 'require|email|unique:member',
        'passwd' => 'require|length:6,18|alphaDash',
        'trade_passwd' => 'require|length:6,18|alphaDash',
        'invite_code' => 'checkInviteCode',
        "is_agent" => 'in:0,1',
        "contract_switch" => 'in:0,1,2',
        "withdraw_status" => 'in:1,-1',
        "status" => 'in:1,-1',
        "audit_status" => "in:3,2",
        "amount" => "require|checkAmount|checkMemberAccount",
        "pay_type" => "require|in:1,2",
        "coin_id" => "require"
    ];

    protected $message = [
        'id.require' => '缺少id',
        'email.require' => '邮箱必须填写',
        'email.email' => '邮箱格式错误',
        'email.unique' => '邮箱存在',
        "passwd.require" => "密码必填",
        "passwd.length" => "密码长度6-18位",
        "passwd.alphaDash" => '密码必须是数字字母下划线组成',
        "trade_passwd.require" => "交易密码必填",
        "trade_passwd.length" => "交易密码长度6-18位",
        "trade_passwd.alphaDash" => '交易密码必须是数字字母下划线组成',
        "is_agent.in" => "代理值错误",
        "audit_status.in" => "审核状态错误",
        "contract_switch.in" => "秒合约风控值错误",
        "withdraw_status.in" => "提现状态值错误",
        "status.in" => "登录状态值错误",
        "amount.require" => "金额必须填写",
        "amount.checkAmount" => "金额格式错误，必须大于0",
        "amount.checkMemberAccount" => "余额不足",
        "pay_type.require" => "类型必须选择",
        "pay_type.in" => "类型错误",
        "coin_id.require" => "币种必须选择"
    ];

    protected $scene = [
        'add' => ['email', "passwd", "trade_passwd"],
        "audit" => ["audit_status", 'id'],
        "agent" => ["id", "is_agent"],
        "status" => ["id", "status"],
        "withdraw_status" => ["id", "withdraw_status"],
        'pay' => ["id", "pay_type", "coin_id", "amount"]
    ];

    public function sceneEdit()
    {
        return $this->only(['passwd', 'trade_passwd', 'is_agent', 'contract_switch', 'id'])
            ->remove('passwd', 'require')
            ->remove("trade_passwd", 'require');
    }

    public function checkAmount($value)
    {
        if (!is_numeric($value)) {
            return false;
        }
        if ($value <= 0) {
            return false;
        }
        return true;
    }

    public function checkMemberAccount($value, $rule, $data = [])
    {
        $member = Db::name("memberCoin")->field("account_amount")
            ->where("member_id", $data["id"])
            ->where("coin_id", $data["coin_id"])
            ->find();
        if ($data["pay_type"] == 2 && (!$member||$member["account_amount"] < $value)) {
            return false;
        }
        return true;
    }
}
